package uk.gov.swmprobation.cplitebase;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.FlickrException;
import com.googlecode.flickrjandroid.photos.Photo;

public class PhotoTools {
	
	private static BitmapFactory.Options getBitmapDetail(String photoLocation){
        BitmapFactory.Options bitmapDetails = new BitmapFactory.Options();
        bitmapDetails.inJustDecodeBounds=true;
    	BitmapFactory.decodeFile(photoLocation,bitmapDetails);
    	return bitmapDetails;
	}
	
	private static Bitmap getBitmap(String photoLocation, int sampleSize){
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = sampleSize;
		Bitmap photoBitmap = BitmapFactory.decodeFile(photoLocation,options);
		return photoBitmap;
	}

	public static Bitmap resizeBitmap(Bitmap bitmap, int limit){
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		double max_size = (double) Math.max(height, width);
		
		if (max_size>limit){
			double scale = max_size/limit;
			width = (int) (width/scale);
			height = (int) (height/scale);
		}
		return Bitmap.createScaledBitmap(bitmap, width, height, false);
	}
	
	public static Bitmap rotateBitmap(Bitmap bitmap, int degrees){
		Matrix matrix = new Matrix();
		matrix.postRotate(degrees);
		return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
	}
	
	private static Bitmap getRotatedBitmap(String photoLocation,int sampleSize,int limit){
		ExifInterface exif;
		int orientation = ExifInterface.ORIENTATION_NORMAL;
		Bitmap returnBitmap = getBitmap(photoLocation,sampleSize);
		if(returnBitmap !=null){
			returnBitmap = resizeBitmap(returnBitmap,limit);
			try {
				exif = new ExifInterface(photoLocation);
				orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, orientation);
				switch (orientation){
					case ExifInterface.ORIENTATION_NORMAL:
						break;
					case ExifInterface.ORIENTATION_ROTATE_90:
						returnBitmap = rotateBitmap(returnBitmap, 90);
						break;
					case ExifInterface.ORIENTATION_ROTATE_180:
						returnBitmap = rotateBitmap(returnBitmap, 180);
						break;
					case ExifInterface.ORIENTATION_ROTATE_270:
						returnBitmap = rotateBitmap(returnBitmap, 270);
						break;
					default:
						break;
				}		
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return returnBitmap;
		
	}
	
	public static Bitmap fitBitmapIn(String photoLocation, int limits){
		Bitmap returnBitmap = null;
		BitmapFactory.Options bitmapDetails = getBitmapDetail(photoLocation);
		if(bitmapDetails!=null){
			double maxsize = Math.max(bitmapDetails.outHeight, bitmapDetails.outWidth);
			int scaleSize = 1;
			if (maxsize>limits){
				scaleSize = (int) Math.ceil(maxsize/limits);
			}
			returnBitmap = getRotatedBitmap(photoLocation,scaleSize,limits);
		}
		return returnBitmap;
	}
	
	public static void saveThumbnail(Project project){
		Log.e("PT","Save Thumbnail");
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
		int max_photo_size = (int) (sharedPref.getInt("Max_Picture_Size", 200)*1.8);
		Bitmap photoBitmap = PhotoTools.fitBitmapIn(project.getImagePath(), max_photo_size);
		if (photoBitmap != null){
			File file=new File(MyApplication.getContext().getFilesDir(),project.getId()+".jpg");
			FileOutputStream fileOutputStream;
			try {
				fileOutputStream = new FileOutputStream(file);
				photoBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream);
				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void deleteThumbnail(int projectId){
		File file=new File(MyApplication.getContext().getFilesDir(),projectId+".jpg");
		if(file !=null){
			file.delete();
		}
	}
	
	public static void deletePhoto(int projectId){
		Project project = DatabaseHandler.getProject(projectId);
		File file=new File(project._image_path);
		if(file !=null){
			file.delete();
		}
	}
	
	public static File getThumbnail (Project project){
		File thumbnail = new File(MyApplication.getContext().getFilesDir(),project.getProjectId()+".jpg");
        if (!thumbnail.exists()){
        	SaveThumbnail savethumbnail = new SaveThumbnail(project._image_path, project._project_id);
        	savethumbnail.execute();
        }
        return thumbnail;
	}
	
	public static boolean photoExists(String filePath){
		File imageFile = new File(filePath);
		return imageFile.exists();
	}
}
